package com.briup;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Arrays;

import org.junit.Test;

import com.mysql.cj.xdevapi.Statement;

public class MysqlTable {
    // 数据库驱动
    String driver = "com.mysql.jdbc.Driver";
    // 数据库连接地址
    String url = "jdbc:mysql://localhost:3306/briup";
    // 数据库用户名
    String username = "briup";
    // 数据库密码
    String password = "briup";
    @Test
    public void createTable()
    {
        Connection conn = null;
        Statement stmt = null;
        // 1. 加载驱动
        try {
            Class.forName(driver);
            // 2. 获取连接
            conn = java.sql.DriverManager.getConnection(url, username, password);
            // 3. 获取数据库操作对象
            stmt = conn.createStatement();
            // 4. 执行sql语句
            String sql = "CREATE DATABASE IF NOT EXISTS jdbc-test";
            stmt.executeUpdate(sql);
            sql = "create table t_customer(id int primary key auto_increment, name varchar(20), age int, birthday date, register_time datetime)";
            // 5. 处理查询结果
            int count = stmt.executeUpdate(sql);
            //输出受影响的行数
            System.out.println(count);
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            //6.释放资源
            try{
                if(stmt != null) stmt.close();
                if(conn != null) conn.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
    // 插入数据
  @Test
  public void insertData() {
    Connection conn = null;
    Statement stmt = null;
    try {
      // 1. 加载驱动
      Class.forName(driver);
      // 2. 获取连接对象
      conn = DriverManager.getConnection(url, username, password);
      // 3. 获取操作对象
      stmt = conn.createStatement();
      // 4. 执行sql语句
//      String sql1 = "insert into t_user(id,name,password,age) values(4,'tom','tom',20)";
//      String sql2 = "insert into t_user(id,name,password,age) values(5,'admin','admin',19)";
//      String sql3 = "insert into t_user(id,name,password,age) values(6,'briup','briup',18)";
      String sql1 = "insert into t_user(id,name,password,age) values(2,'张三','张三',30)";

//       int rows = stmt.executeUpdate(sql);
      // 执行多个sql语句
      stmt.addBatch(sql1);
//      stmt.addBatch(sql2);
//      stmt.addBatch(sql3);
//      stmt.addBatch(sql4);
      // 开始处理
      int[] rows = stmt.executeBatch();
      // 5. 处理结果
      System.out.println("修改的行数 rows：" + Arrays.toString(rows));
    } catch (Exception e) {
      // 6. 释放资源
      if (stmt != null) {
        try {
          stmt.close();
        } catch (Exception exc) {
          exc.printStackTrace();
        }
      }
      if (conn != null) {
        try {
          conn.close();
        } catch (Exception exc) {
          exc.printStackTrace();
        }
      }
    }
  }
   

        
    

}
